package com.hk.service.business.chrome;

import com.hk.utils.ConstantUtil;
import com.qeagle.devtools.launch.ChromeArguments;
import com.qeagle.devtools.launch.ChromeLauncher;
import com.qeagle.devtools.protocol.types.page.PrintToPDF;
import com.qeagle.devtools.protocol.types.page.PrintToPDFTransferMode;
import com.qeagle.devtools.services.ChromeDevToolsService;
import com.qeagle.devtools.services.ChromeService;
import com.qeagle.devtools.services.types.ChromeTab;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

@Slf4j
@Service
public class ChromeDriverService {

    @Value("${chrome.location:C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe}")
    private String chromelocation;

    @Value("${target.url:https://blog.csdn.net/zhou_guo_quan/article/details/122304338}")
    private String targetUrl;

    @Value("${pdf.temp.filepath:D:\\file\\pdfxml\\}")
    private String pdfTempFilePath;

    @Autowired
    private ReportPdfService reportPdfService;


    /**
     * 生成pdf文件
     */
    public void generatePdf() {
        try {
            String pdfFile = generatePdfFile(targetUrl, pdfTempFilePath);
            reportPdfService.uploadFile(pdfFile);
            //删除临时文件
            File outFile = new File(pdfFile);
            outFile.delete();
        } catch (Exception e) {
            log.error("生成pdf失败，原因：{}", e);
        }

    }

    private String generatePdfFile(String actionUrl, String resultPath) throws Exception {
        log.info("ChromeDriverService.generatePdfFile=" + actionUrl);
        String pdfPath = null;
        //页面缩放比例
        Double scale = 1.41;
        //页面跨度,像素
        Double paperWidth = 8.75;
        // Create chrome launcher.
        ChromeLauncher launcher = new ChromeLauncher();
        try {

            ChromeArguments chromeArguments = ChromeArguments.defaults(true).additionalArguments("no-sandbox", true).build();
            Path path = Paths.get(chromelocation);

            // Launch chrome either as headless (true) or regular (false).
            ChromeService chromeService = launcher.launch(path, chromeArguments);

            // Create empty tab ie about:blank.
            ChromeTab tab = chromeService.createTab();

            // Get DevTools service to this tab
            ChromeDevToolsService devToolsService = chromeService.createDevToolsService(tab);

            devToolsService.getPage().navigate(actionUrl);
            Thread.sleep(15000);
            Double height = devToolsService.getPage().getLayoutMetrics().getContentSize().getHeight();
            height = Math.ceil(height / 96);
            Thread.sleep(5000);
            PrintToPDF printToPDF = devToolsService.getPage().printToPDF(false, false, true,
                    scale, 8.268, 11.693, 0.0, 0.0, 0.0, 0.0, "",
                    false, "", "", false, PrintToPDFTransferMode.RETURN_AS_BASE_64);

            //写入pdf文件
            String uuid = ConstantUtil.getUUID();
            pdfPath = resultPath + uuid + ".pdf";
            storeAsFile(pdfPath, printToPDF.getData());

            chromeService.closeTab(tab);
            devToolsService.close();
        } catch (Exception e) {
            log.error("ChromeDriverService.generatePdfFile异常,actionUrl=" + actionUrl, e);
        } finally {
            launcher.close();
        }
        log.info("ChromeDriverService.generatePdfFile结束!");
        return pdfPath;
    }

    private static void storeAsFile(String fileName, String data) {
        FileOutputStream fileOutputStream = null;
        try {
            File file = new File(fileName);
            fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(Base64.getDecoder().decode(data));
        } catch (IOException var12) {
            log.error("ChromeDriverService.storeAsFile异常,", var12);
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                } catch (IOException var11) {
                    log.error("ChromeDriverService.storeAsFile异常,", var11);
                }
            }
        }
    }


}
